package love.simbot.example.utils.http;


import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpHead;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

// 发送Http请求的包
public abstract class HttpUtils {

    private static final String ClientMark = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.66 Safari/537.36 Edg/103.0.1264.44";


    // Get请求
    public static <V> String getTool(String url,Map<String,V> paramMap){
        // 1.首先拥有一个浏览器
        CloseableHttpClient client = HttpClientBuilder.create().build();

        // 2.构建参数
        HttpGet httpGet = null;
        if(paramMap != null) {
            StringBuffer params = new StringBuffer();
            paramMap.forEach((k, v) -> {
                if (paramMap.size() == 1) {
                    params.append(k + "=");
                    params.append(v);
                    return;
                }
                params.append(k + "=");
                params.append(v);
                params.append("&");
            });


            // 创建Get请求
            httpGet = new HttpGet(url + "?" + params);
        }else{
            httpGet = new HttpGet(url);
        }
        // 响应模型
        CloseableHttpResponse response = null;
        httpGet.addHeader("user-agent",ClientMark);
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(40000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(40000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(40000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = client.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (response.getStatusLine().getStatusCode()==200 && responseEntity != null) {
                //System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));
                String result = EntityUtils.toString(responseEntity);
                return result;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (client != null) {
                    client.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    // Post请求
    public static  String getPostTool(String url, Map<String,String> paramsMap,Map<String,String> header){
        // 1.首先拥有一个浏览器
        CloseableHttpClient client = HttpClientBuilder.create().build();
        // 构建参数
        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
        paramsMap.forEach((k,v)->{
            paramsList.add(new BasicNameValuePair(k,v));
        });
        StringEntity paramEntity = null;
        try {
            paramEntity  = new UrlEncodedFormEntity(paramsList,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        HttpPost post = new HttpPost(url);
        post.setEntity(paramEntity);
        // 添加请求头
        header.forEach((k,v)->{
            post.addHeader(k,v);
        });


        // 执行post请求
        CloseableHttpResponse execute = null;
        try {
            execute = client.execute(post);
            if(execute.getStatusLine().getStatusCode() == 200){
                HttpEntity entity = execute.getEntity();
                String result = EntityUtils.toString(entity, "utf-8");
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (execute!=null){
                try {
                    execute.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return  null;
    }

}
